import {
  WifiOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import './style.scss';
import { Drawer, Button, Spin } from 'antd';
import { getSysUserInfo } from 'seats/servers/servers';
import { WAudio } from 'components/UILibrary/wAudio';

/**设备检测 */
const DeviceCheck: React.FC = () => {
  const [visible, setVisible] = useState<boolean>(false); // 是否显示弹窗
  const [exploreStatus, setExploreStatus] = useState(1); //浏览器状态 ;1 - loading ; 2- fail ; 3- ok;
  const [netStatus, setNetStatus] = useState(1); //网络状态； 1 - loading ; 2- fail ; 3- ok;
  const videoRef = useRef(null); // audio组件 测试麦克风
  const bgVideoRef = useRef(null); // audio组件 背景音乐

  /**
   * 显示抽屉盒
   */
  const showDrawer = () => {
    setVisible(true);
  };

  /**
   * 隐藏抽屉盒
   */
  const onClose = () => {
    setVisible(false);
  };

  /**
   * 睡眠
   */
  function sleep(time: number) {
    return new Promise(resolve => setTimeout(resolve, time));
  }

  /**
   * 浏览器检测
   */
  const exploreCheck = useCallback(async () => {
    const userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
    console.log(userAgent);
    const isFirefox = userAgent.indexOf('Firefox') > -1; // 是否是火狐  ，火狐内核Gecko
    console.log('火狐' + isFirefox); // 返回 true  则是 ，false  则不是
    const isChrome = userAgent.indexOf('Chrome') > -1; // 是否是谷歌
    console.log('谷歌' + isChrome); // 返回 true  则是 ，false  则不是
    await sleep(2000);
    setExploreStatus(isFirefox || isChrome ? 3 : 2);
  }, []);

  /**
   * 网络检测
   */
  const netCheck = useCallback(async () => {
    await sleep(3000);
    try {
      await getSysUserInfo();
      setNetStatus(3);
    } catch (e) {
      setNetStatus(2);
    }
  }, []);

  /**
   * 麦克风和扬声器检测
   */
  const checkDevice = useCallback(() => {
    console.log('麦克风和扬声器检测*****begin');
    // 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
    if (navigator.mediaDevices === undefined) {
      //@ts-ignore
      navigator.mediaDevices = {};
    }

    // 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
    // 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
    if (navigator.mediaDevices.getUserMedia === undefined) {
      navigator.mediaDevices.getUserMedia = function (constraints) {
        // 首先，如果有getUserMedia的话，就获得它
        //@ts-ignore
        const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

        // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
        if (!getUserMedia) {
          return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
        }

        // 否则，为老的navigator.getUserMedia方法包裹一个Promise
        return new Promise(function (resolve, reject) {
          getUserMedia.call(navigator, constraints, resolve, reject);
        });
      };
    }

    navigator.mediaDevices
      .getUserMedia({ audio: true })
      .then(function (stream) {
        if (!videoRef || !videoRef.current) return;
        const video = videoRef.current;
        // 旧的浏览器可能没有srcObject
        // @ts-ignore
        if ('srcObject' in video) {
          // @ts-ignore
          video.srcObject = stream;
        } else {
          // 防止在新的浏览器里使用它，应为它已经不再支持了
          // @ts-ignore
          video.src = window.URL.createObjectURL(stream);
        }
        // @ts-ignore
        video.onloadedmetadata = function () {
          // @ts-ignore
          video.play();
        };
      })
      .catch(function (err) {
        console.log(err.name + ': ' + err.message);
      });
  }, []);

  /**
   * 语音暂停回调
   */
  const audioPause = () => {
    if (!videoRef || !videoRef.current) return;
    const video = videoRef.current;
    // @ts-ignore
    video.pause();
  };

  /**
   * 关闭背景音乐
   */
  const stopBGvideo = () => {
    if (bgVideoRef && bgVideoRef.current) {
      //@ts-ignore
      bgVideoRef.current.pauseAudio();
    }
  };

  /**
   * 重新检测
   */
  const reCheck = () => {
    setExploreStatus(1);
    setNetStatus(1);
    exploreCheck();
    netCheck();
    stopBGvideo();
  };

  useEffect(() => {
    if (visible) {
      exploreCheck();
      netCheck();
    } else {
      setExploreStatus(1);
      setNetStatus(1);
      audioPause();
      stopBGvideo();
    }
  }, [exploreCheck, netCheck, visible]);

  return (
    <>
      {/* 检测麦克风说话 */}
      <audio ref={videoRef} />
      <div className="layout-header-notice">
        <Button
          key={'tool_' + visible}
          className="notice-btn"
          type="primary"
          shape="round"
          icon={<WifiOutlined />}
          onClick={showDrawer}
        >
          设备检测
        </Button>
      </div>
      <Drawer
        title="设备检测"
        width={520}
        onClose={onClose}
        visible={visible}
        bodyStyle={{ paddingBottom: 80 }}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={reCheck} type="primary">
              重新检测
            </Button>
          </div>
        }
      >
        <div className="device-check">
          <div className="item llq-check-box">
            <div className="title">浏览器检测</div>
            {exploreStatus === 1 && (
              <div className="loading">
                <Spin />
                <span>正在检测</span>
              </div>
            )}
            {exploreStatus === 3 && (
              <div className="ok align-cen">
                <CheckCircleOutlined className="color_green" style={{ fontSize: '25px' }} />
                <span>浏览器符合要求</span>
              </div>
            )}
            {exploreStatus === 2 && (
              <div className="fail align-cen">
                <CloseCircleOutlined className="color_red" style={{ fontSize: '25px' }} />
                <span>请使用Chrome或者FireFox浏览器</span>
              </div>
            )}
          </div>

          <div className="item">
            <div className="title">网络检测</div>
            {netStatus === 1 && (
              <div className="loading">
                <Spin />
                <span>正在检测</span>
              </div>
            )}
            {netStatus === 3 && (
              <div className="ok align-cen">
                <CheckCircleOutlined className="color_green" style={{ fontSize: '25px' }} />
                <span>网络正常</span>
              </div>
            )}
            {netStatus === 2 && (
              <div className="fail align-cen">
                <CloseCircleOutlined className="color_red" style={{ fontSize: '25px' }} />
                <span>网络异常，请检查网络连接</span>
              </div>
            )}
          </div>

          <div className="item">
            <div className="title">语音设备检测</div>
            <div className="box">
              <ExclamationCircleOutlined className="color_orange" />
              <span>
                请先播放音乐背景，然后对着麦克风说话，判断能否从耳麦中听见背景音乐和自己的声音，如果能听见，则设备正常，如果不能听见，请调整扬声器和麦克风再检测
              </span>
            </div>
            {/*背景音乐*/}
            <WAudio
              ref={bgVideoRef}
              id="checkDeviceAudio"
              src="/webseats/yudeyinji.wav"
              onAudioPlay={checkDevice}
              onAudioPause={audioPause}
            />
          </div>
        </div>
      </Drawer>
    </>
  );
};

export default DeviceCheck;
